<script setup lang="ts">
import { computed, ref } from "vue";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";

import Stall from "./components/Stall.vue";
import Page from "@/components/common/Page.vue";
import ByButton from "@/components/ui/ByButton.vue";

import useFetch from "@/hooks/useFetch";
import ApiActivity from "@/api/activity";
import useMerchant from "@/stores/merchant";

import { TActivity, TActivityApply } from "@/global";
import { richTextFormater } from "@/utils";
import useSubscribeMessage from "@/hooks/useSubscribeMessage";

const { params } = useRouter<{
  // 活动ID
  act_id: string;
  // 商户ID
  m_id: string;
  // 报名记录ID
  id: string;
}>();

const applyId = +params.id;

const { merchantData } = useMerchant();

// 商户ID
const merchantID = computed(() => merchantData?.id || +params.m_id);

// 展位ID
const standId = ref(0);

// 查询活动详情
const { data: activityData } = useFetch<TActivity>(ApiActivity.activityDetail, {
  defaultParams: { id: +params.act_id },
  afterFetch: (res: any) => res.detail,
});

// 查询报名活动数据
const {
  loading: loadingApplyDetail,
  data: applyDetail,
  run: runApplyDetail,
} = useFetch<TActivityApply>(ApiActivity.getApplyActivityDetail, {
  immediate: false,
  afterFetch: (data: any) => data.detail,
  onSuccess(detail) {
    // 设置已选展位信息
    standId.value = detail.stand_id!;
  },
});

// 打开页面就查询一次
useDidShow(() => !!applyId && runApplyDetail({ id: applyId }));

function getResultPath(id) {
  const { act_id, m_id } = params;

  return `/packageMerchant/pages/enroll/result?id=${id}&act_id=${act_id}&m_id=${m_id}`;
}

// 提交报名
const { loading: loadingApply, run: runApply } = useFetch<{ id: number }>(
  ApiActivity.applyActivity,
  {
    immediate: false,
    onSuccess(res) {
      Taro.redirectTo({ url: getResultPath(res.id) });
    },
  }
);

// 订阅方法：报名
const subscribe = useSubscribeMessage("enroll");

// 处理按钮事件
const handleBtnTap = async () => {
  if (applyId) {
    const detail = applyDetail.value;
    const { deposit_status = 0 } = detail;
    if (deposit_status > 0) return;
    
    // 已报名
    Taro.navigateTo({ url: getResultPath(applyId) });
  } else {
    // 未报名

    // 是否已选展位
    if (!standId.value) {
      Taro.showToast({ icon: "none", title: "请选择展位" });
      return;
    }

    // 二次确认
    const { confirm } = await Taro.showModal({
      title: "确定报名该活动？",
      content: "点击报名之后，如因自身原因退出超过3次，将无法再参加任何活动哦",
    });

    if (confirm) {
      await subscribe();

      // 去报名
      runApply({
        act_id: +params.act_id,
        merchant_id: +params.m_id,
        stand_id: standId.value,
      });
    }
  }
};

const auditStatusText = {
  0: "报名审核中",
  1: "审核通过",
  2: "报名未通过",
};
//押金状态 0 未交 1 已交 2 已退
const depostStatusText = {
  0: "待交押金",
  1: "已交押金",
  2: "押金已退回",
};

// 按钮文本
const buttonView = computed(() => {
  const detail = applyDetail.value;

  let text = "立即报名";
  let fail = false;
  let dark = true;

  if (detail) {
    const { audit_status, deposit_status = 0 } = detail;

    // switch (audit_status) {
    //   case 0: text = '查看进度'; break;
    //   case 2: text = "报名未通过", fail = audit_status == 2; break;
    //   default: text = deposit_status == 0 ? '待交押金' : '已报名';
    // }
    text =
      audit_status == 1
        ? depostStatusText[deposit_status]
        : auditStatusText[audit_status];

    dark = !fail && deposit_status == 0;
  }

  return {
    text,
    fail,
    dark,
  };
});

// banner图
const swiperList = computed(() => {
  const { title_img, pic_content } = activityData.value || {};
  if (pic_content || title_img) {
    return (pic_content || title_img).split(";");
  }
  return [];
});
</script>

<template>
  <Page hiddenHeaderBg footerSticky>
    <template #footer v-if="merchantID">
      <view class="bg-light">
        <view
          class="flex items-center py-4 px-5"
          :class="[
            !applyDetail || applyDetail?.audit_status == 2
              ? 'justify-center'
              : 'justify-between',
          ]"
        >
          <view
            v-if="applyDetail && applyDetail.audit_status != 2"
            class="text-dark"
          >
            <template v-if="applyDetail.deposit_status == 1">
              <text class="text-2xl"
                >已交押金￥{{ applyDetail.deposit_amount / 100 }}</text
              >
              <view class="text-xs">活动结束将在15个工作日内返还</view>
            </template>
            <text v-else-if="applyDetail.deposit_status == 2" class="text-2xl">
            </text>
            <text v-else class="text-2xl">已提交报名</text>
          </view>

          <ByButton
            class="w-[360px]"
            :class="{
              'bg-error': buttonView.fail,
              'bg-dark': buttonView.dark,
            }"
            :loading="loadingApply || loadingApplyDetail"
            @tap="handleBtnTap"
          >
            {{ buttonView.text }}
          </ByButton>
        </view>
        <view class="safe-footer" />
      </view>
    </template>

    <view class="mx-5 my-2">
      <view class="text-right">
        <view
          class="inline-block px-1 pt-1 pb-4 rounded-lg text-light bg-error text-sm"
        >
          🔥火热报名中
        </view>
      </view>

      <view class="relative p-3 bg-primary rounded-lg -mt-3">
        <!-- S 轮播图 -->
        <swiper
          class="h-[464px]"
          indicator-active-color="rgba(0,0,0,.6)"
          :indicator-dots="true"
          :autoplay="swiperList.length > 1"
          :circular="swiperList.length > 1"
        >
          <swiper-item v-for="(item, index) in swiperList" :key="index">
            <image :src="item" class="w-full h-full rounded-md" />
          </swiper-item>
        </swiper>
        <!-- E 轮播图 -->

        <!-- S 基本信息 -->
        <view class="mt-2 text-light text-xl">{{ activityData?.title }}</view>

        <view
          class="flex items-center mt-2 h-[72px] bg-white rounded-full px-3 text-dark"
        >
          <text class="text-sm">时间</text>
          <view class="ml-2.5 text-xs whirespace-pre">{{
            activityData?.act_time
          }}</view>
        </view>

        <view
          class="flex items-center mt-2 h-[72px] bg-white rounded-full px-3 text-dark"
        >
          <text class="flex-none text-sm">地点</text>
          <view class="flex-auto ml-2.5 text-xs line-clamp">
            {{ activityData?.street || activityData?.address }}
          </view>
          <!-- <image src="/static/images/location.png" class="flex-none ml-3 w-[42px]" mode="widthFix" /> -->
        </view>
        <!-- E 基本信息 -->

        <!-- S 活动介绍-->
        <template v-if="activityData?.desc">
          <view class="mt-6 text-light text-xl pb-2 border-b-1 border-light"
            >活动简介</view
          >
          <view class="my-3">
            <rich-text :nodes="richTextFormater(activityData?.desc)" />
          </view>
        </template>
        <!-- E 活动介绍 -->

        <!-- S 展位选择 -->
        <view class="mt-6 text-light text-xl pb-2 border-b-1 border-light"
          >展位选择</view
        >
        <view class="my-3">
          <Stall
            v-model="standId"
            :actId="+params.act_id"
            :merchantID="merchantID"
            :disabled="!!applyDetail"
          />
        </view>
        <!-- E 展位选择 -->
      </view>
    </view>
  </Page>
</template>
